package com.coolw.test.sftp.spring;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * sftp 客户端,单线程使用
 *
 * @author coolw
 * @date 2023/11/6 9:16
 */
@Slf4j
@Component
public class SftpSingleClient {

    private Session session;
    private ChannelSftp channelSftp;

    @Autowired
    private SftpConfig config;

    public void connect() throws JSchException {
        JSch jsch = new JSch();

        // 新建会话
        session = jsch.getSession(config.getUsername(), config.getHost(), config.getPort());
        session.setPassword(config.getPassword());
        // 跳过第一次连接时的确认提示
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();

        // 获取通信通道
        Channel channel = session.openChannel("sftp");
        channel.connect();

        channelSftp = (ChannelSftp) channel;
        log.info("连接sftp服务器成功");
    }

    public void disconnect() {
        if (channelSftp != null && !channelSftp.isConnected()) {
            channelSftp.disconnect();
        }
        if (session != null && !session.isConnected()) {
            session.disconnect();
        }
    }
}
